package com.dayaokeji.imkitwrapper.fragment;

import android.app.ActivityManager;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.util.Log;

import com.beetle.im.IMService;

import java.util.List;

/**
 * ********************************************************************
 * *  Created by Zeno on 2018/6/23
 * ********************************************************************
 * *  version 1.0
 * ********************************************************************
 * *  Copyright (C) dayaokeji.com 2018 -- 2020 All rights reserved.
 * ********************************************************************
 * * base fragment
 * ********************************************************************
 */
public class BaseFragment extends Fragment {


    @Override
    public void onResume() {
        super.onResume();
        IMService.getInstance().enterForeground();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (!isAppOnForeground()) {
            //app 进入后台,停止IMService,采用push机制接收离线消息
            Log.i("im", "app enter background");
//            IMService.getInstance().enterBackground();
        }
    }

    /**
     * 程序是否在前台运行
     *
     * @return
     */
    public boolean isAppOnForeground() {
        // Returns a list of application processes that are running on the
        // device
        if (getActivity() != null) {
            ActivityManager activityManager =
                    (ActivityManager) getActivity().getApplicationContext().getSystemService(
                            Context.ACTIVITY_SERVICE);
            String packageName = getActivity().getApplicationContext().getPackageName();

            List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                    .getRunningAppProcesses();
            if (appProcesses == null)
                return false;

            for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
                // The name of the process that this object is associated with.
                if (appProcess.processName.equals(packageName)
                        && appProcess.importance
                        == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    return true;
                }
            }

            return false;
        }else{
            return false;
        }
    }
}
